﻿using Microsoft.SharePoint;
using InfoJetSoft.Service.Util;

namespace ServBus.ListForm2010.Extension
{
    public class RelativeUrlResolver : IRelativeUrlResolver
    {
        private string templateUrl = null;

        public RelativeUrlResolver(string templateUrl)
        {
            this.templateUrl = templateUrl;
        }

        #region IRelativeUrlResolver 成员
        public string resolve(string folderUrl)
        {
            string lowerUrl = folderUrl.ToLower();
            if (lowerUrl.StartsWith("http://") || lowerUrl.StartsWith("https://"))
            {
                //folderUrl is absolute url.
                return folderUrl;
            }
            else
            {
                string url = lowerUrl;
                if (lowerUrl.Contains("../") && templateUrl.ToLower() != null)
                {
                    int count = 0;
                    while (lowerUrl.IndexOf("../") == 0)
                    {
                        lowerUrl = lowerUrl.Substring(3);
                        count++;
                    }
                    url = templateUrl.ToLower();
                    for (int i = 0; i < (count + 1); i++)
                    {
                        int index = url.LastIndexOf("/");
                        if (index > 0)
                        {
                            url = url.Substring(0, index);
                        }
                        else if (index == 0)
                        {
                            url = "";
                        }
                    }
                    if (lowerUrl.StartsWith("/") || lowerUrl.StartsWith("\\"))
                    {
                        url = url + lowerUrl;
                    }
                    else
                    {
                        url = url + "/" + lowerUrl;
                    }
                    if (!(url.EndsWith("/") || url.EndsWith("\\")))
                    {
                        url = url + "/";
                    }
                    if (!templateUrl.StartsWith("http://") && !templateUrl.StartsWith("https://"))
                    {
                        url = SPContext.Current.Web.Url + url;

                    }
                }
                //folderUrl is relative url.
                // templateUrl, http://sharepoint/form1/forms/template.xsn
                // folderUrl, ../ 或 ../../ 或 ../../Lists/List/ 等
                // result, http://sharepoint/form1/ 等
                //ErrorLog.Write("lowerUrl" + lowerUrl, System.Diagnostics.EventLogEntryType.Warning);
                return url;
            }
        }
        #endregion

    }
}
